<template>
  <div class="drawer-main">
    <div class="module-selector-header" v-if="current_num > 10">
      <div class="module-count-info">
        <span>当前网关设备总数: {{ current_num }}</span>
        <span>当前页: {{ currentPage }}/{{ totalPages }}</span>
      </div>
      <div class="pagination-controls">
        <el-button 
          size="small" 
          :disabled="currentPage === 1" 
          @click="prevPage"
          icon="ArrowLeft"
        >
          上一页
        </el-button>
        <el-button 
          size="small" 
          :disabled="currentPage === totalPages" 
          @click="nextPage"
          icon="ArrowRight"
        >
          下一页
        </el-button>
      </div>
    </div>
    
    <div class="all_modules_layout">
      <div
        style="margin-right: 0px;"
        v-for="module in paginatedModules" 
        :key="module.id"
        class="module-button"
        :class="{ 'is-active': module.isChecked, 'is-flashing': module.isFlashing }"
        @click="handleModuleClick(module.id)"
        size="large"
      >
        <div class="button-content">
          <!-- Top Status Indicators -->
          <div class="module-status-indicators">
            <!-- 电量显示 (for all) -->
            <div v-if="module.powerType === 'battery' && module.batteryLevel !== undefined" class="battery-indicator">
              <div class="battery-icon" :class="getBatteryClass(module.batteryLevel)">
                <div class="battery-level" :style="{ width: module.batteryLevel + '%' }"></div>
              </div>
              <span class="battery-text">{{ Math.round(module.batteryLevel) }}%</span>
            </div>
            <!-- 常规信号强度显示 (not for module 10) -->
            <div v-if="!isVerticalIndicators(module) && module.signalStrength !== undefined" class="signal-indicator" :class="getSignalStrengthClass(module.signalStrength)">
              <div 
                v-for="i in 5" 
                :key="i" 
                class="signal-bar" 
                :class="{ 'active': i <= (module.signalStrength || 0) + 1 }"
              ></div>
              <span class="indicator-text">{{ module.signal }}dBm</span>
            </div>
          </div>

          <img :src="module.isChecked ? activeImage : defaultImage" class="module-icon" />
          <span class="module-name" :class="{ 'long-name': isLongName(module.deviceName) }">{{ module.deviceName }}</span>
          
          <!-- Bottom Status Indicator for module 10 -->
          <div v-if="isVerticalIndicators(module) && module.signalStrength !== undefined" class="module-status-indicators-bottom">
            <div class="signal-indicator" :class="getSignalStrengthClass(module.signalStrength)">
                <div 
                  v-for="i in 5" 
                  :key="i" 
                  class="signal-bar" 
                  :class="{ 'active': i <= (module.signalStrength || 0) + 1 }"
                ></div>
                <span class="indicator-text">{{ module.signal }}dBm</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import activeImage from '@/assets/module.active.png'
import defaultImage from '@/assets/module.png'
import { onMounted, onUnmounted, ref, watch, computed } from 'vue';
import { gatewayStore } from '@/store/gateway';
import { storeToRefs } from 'pinia';
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue';
import { moduleStore } from '@/store/module';

const gateway_store = gatewayStore()
const { currentIp } = storeToRefs(gateway_store)
const module_store = moduleStore()
const { current_num } = storeToRefs(module_store)

const props = defineProps<{
  moduleList: Module[];
  isZoomed: boolean;
}>();

const localModuleList = ref<Module[]>([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10); // 每页显示10个监测点

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(current_num.value / pageSize.value);
});

// 计算当前页的监测点
const paginatedModules = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return localModuleList.value.slice(start, end);
});

// 分页控制方法
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
  }
};

const handlePageChange = (page: number) => {
  currentPage.value = page;
};

watch(() => props.moduleList, (newVal) => {
  if (localModuleList.value.length === 0 || localModuleList.value.length !== newVal.length) {
    localModuleList.value = newVal.map(m => ({ 
      ...m, 
      isFlashing: m.isFlashing || false,
    }));
    console.log('初始化moduleList', localModuleList.value.length)
  } else if (localModuleList.value.length == newVal.length) {
    // 更新名称
    newVal.forEach(propModule => {
      const localModule = localModuleList.value.find(m => m.id === propModule.id);
      if (localModule) {
        localModule.deviceName = propModule.deviceName;
      }
    });

    // 防止更改名称之后闪光消失
    newVal.forEach(propModule => {
      const localModule = localModuleList.value.find(m => m.id === propModule.id);
      if (localModule) {
        localModule.isChecked = propModule.isChecked;
      }
    });
  }
  
  // 如果当前选中的监测点不在当前页，自动跳转到对应页面
  const activeModule = localModuleList.value.find(m => m.isChecked);
  if (activeModule) {
    const activeIndex = localModuleList.value.findIndex(m => m.id === activeModule.id);
    const targetPage = Math.ceil((activeIndex + 1) / pageSize.value);
    if (targetPage !== currentPage.value) {
      currentPage.value = targetPage;
    }
  }
}, { immediate: true, deep: true });

const flashTimers = new Map<number, number>();

const handleFlashEvent = (event: CustomEvent) => {
  if (props.isZoomed) return;
  if (event.detail.type === 'flash') {
    const targetId = Number(event.detail.ID);
    const index = localModuleList.value.findIndex(m => m.id === targetId);
    if (index !== -1) {
      if (!localModuleList.value[index].isFlashing) {
        const updatedModule = { ...localModuleList.value[index], isFlashing: true };
        localModuleList.value.splice(index, 1, updatedModule);
      }
      
    }
  } else if (event.detail.type === 'stopFlash') {
    // 🔥 新增：处理单个设备停止闪光事件
    const targetId = Number(event.detail.ID);
    const index = localModuleList.value.findIndex(m => m.id === targetId);
    if (index !== -1 && localModuleList.value[index].isFlashing) {
      const updatedModule = { ...localModuleList.value[index], isFlashing: false };
      localModuleList.value.splice(index, 1, updatedModule);
      console.log(`💡 [DEBUG] 设备 ${targetId} 闪光效果已移除`);
    }
  } else if (event.detail.type === 'batteryUpdate') {
    // 处理电量更新事件
    const targetId = Number(event.detail.deviceId);
    const batteryLevel = event.detail.batteryLevel;
    const gatewayIp = event.detail.gatewayIp;
    const index = localModuleList.value.findIndex(m => m.id === targetId && currentIp.value === gatewayIp);
    if (index !== -1) {
      const updatedModule = { 
        ...localModuleList.value[index], 
        batteryLevel: batteryLevel,
        powerType: 'battery' // 有电量数据说明是电池供电
      };
      localModuleList.value.splice(index, 1, updatedModule);
      console.log(`🔋 [DEBUG] 设备 ${targetId} 电量更新: ${batteryLevel}%`);
    }
  } else if (event.detail.type === 'signalUpdate') {
    // 处理信号强度更新事件
    const targetId = Number(event.detail.deviceId);
    const signalStrength = event.detail.signalStrength;
    const gatewayIp = event.detail.gatewayIp;
    const index = localModuleList.value.findIndex(m => m.id === targetId && currentIp.value === gatewayIp);
    if (index !== -1) {
      const updatedModule = { 
        ...localModuleList.value[index], 
        signal: event.detail.signal,
        signalStrength: signalStrength,
      };
      localModuleList.value.splice(index, 1, updatedModule);
      console.log(`📶 [DEBUG] 设备 ${targetId} 信号强度更新: ${signalStrength}`);
    }
  } else if (event.detail.type === 'reset') { 
    localModuleList.value.forEach(module => {
      module.isFlashing = false;
    });
    flashTimers.forEach(timerId => clearTimeout(timerId));
    flashTimers.clear();
  } else if (event.detail.type === 'taggleGateway' || event.detail.type === "deviceListUpdate") {
      try {
       const currentModuleList = JSON.parse(event.detail.data)
       currentModuleList.forEach((module: Module) => {
         const index = localModuleList.value.findIndex(m => m.id === module.id);
         if (index !== -1) {
           const updatedModule = { ...localModuleList.value[index], isChecked: module.isChecked, isFlashing: module.isFlashing };
           localModuleList.value.splice(index, 1, updatedModule);
         }
       })
     } catch(error) {
      console.log('解析失败：' + error)
     }
  } 
};

onMounted(() => {
  window.addEventListener("custom-event", handleFlashEvent as EventListener);
});

onUnmounted(() => {
  window.removeEventListener("custom-event", handleFlashEvent as EventListener);
  // Clear all timers when the component is unmounted
  flashTimers.forEach(timerId => clearTimeout(timerId));
});

interface Module {
  id: number;
  deviceName: string;
  isChecked: boolean;
  isFlashing: boolean; // 确保 isFlashing 属性始终存在
  batteryLevel?: number; // 电量百分比
  powerType?: 'battery' | 'wired'; // 供电类型
  signalStrength?: number; // 新增: 信号强度 (0-4)
  signal?: number; // 新增: 信号值
}

const emit = defineEmits<{
  (e: 'select', id: number): void
}>()

const handleModuleClick = (id: number) => {
  emit('select', id);
}

// 检查设备名称是否过长
const isLongName = (name: string): boolean => {
  return Boolean(name && name.length > 10);
};

// 获取电量图标样式类
const getBatteryClass = (batteryLevel: number): string => {
  if (batteryLevel > 70) return 'battery-high';
  if (batteryLevel > 30) return 'battery-medium';
  return 'battery-low';
};

// 获取信号强度CSS类
const getSignalStrengthClass = (strength: number | undefined): string => {
  if (strength === undefined || strength === null) return 'signal-none';
  if (strength >= 4) return 'signal-excellent';
  if (strength === 3) return 'signal-good';
  if (strength === 2) return 'signal-fair';
  if (strength === 1) return 'signal-poor';
  return 'signal-none';
};

// 指示栏是否垂直排列（仅针对“监测点10”）
const isVerticalIndicators = (module: Module): boolean => {
  if (!module) return false;
  // 同时兼容 id 为 10 或 deviceName 包含“监测点10”
  return module.id === 10
};
</script>

<style scoped lang="less">
.font-wrap {
  writing-mode: vertical-lr;
  text-orientation: mixed;
  margin-top: 5px;
  font-size: 12px;
  line-height: 1.3;
  max-height: 100px;
  overflow: hidden;
  text-align: center;
}

.drawer-main {
  padding: 10px 0;
  width: 100%;
  height: 36%;
  min-height: 200px;
  display: flex;
  flex-direction: column;
  
  .module-selector-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 18px 10px;
    border-bottom: 1px solid rgba(45, 74, 107, 0.3);
    margin-bottom: 10px;
    
    .module-count-info {
      display: flex;
      gap: 20px;
      font-size: 12px;
      color: #e2e8f0;
      
      span {
        opacity: 0.8;
      }
    }
    
    .pagination-controls {
      display: flex;
      gap: 8px;
      
      :deep(.el-button) {
        background: rgba(45, 74, 107, 0.3);
        border-color: #2d4a6b;
        color: #e2e8f0;
        
        &:hover:not(:disabled) {
          background: rgba(45, 74, 107, 0.5);
          border-color: #3d5a7d;
        }
        
        &:disabled {
          opacity: 0.3;
        }
      }
    }
  }
  
  .all_modules_layout {
    flex: 1;
    display: grid;
    grid-template-columns: repeat(3, 1fr) 15%;
    grid-template-rows: repeat(3, 1fr);
    gap: 6px;
    padding: 0 10px;
    border-radius: 12px;
    backdrop-filter: blur(10px);

    > * {
      align-self: stretch;
      justify-self: stretch;
    }

     > *:nth-child(10) {
      grid-column: 4;
      grid-row: 1 / 4;
      .button-content {
        justify-content: center; // Center icon and name
      }
    }
  }
  
  .module-selector-footer {
    padding: 10px 18px 0;
    display: flex;
    justify-content: center;
    border-top: 1px solid rgba(45, 74, 107, 0.3);
    margin-top: 10px;
    
    :deep(.el-pagination) {
      .el-pager li {
        background: rgba(45, 74, 107, 0.3);
        border-color: #2d4a6b;
        color: #e2e8f0;
        
        &:hover {
          background: rgba(45, 74, 107, 0.5);
          border-color: #3d5a7d;
        }
        
        &.is-active {
          background: #409eff;
          border-color: #409eff;
          color: white;
        }
      }
      
      .btn-prev, .btn-next {
        background: rgba(45, 74, 107, 0.3);
        border-color: #2d4a6b;
        color: #e2e8f0;
        
        &:hover:not(:disabled) {
          background: rgba(45, 74, 107, 0.5);
          border-color: #3d5a7d;
        }
        
        &:disabled {
          opacity: 0.3;
        }
      }
    }
  }

  .module-button {
    width: 100%;
    height: 100%;
    min-height: 65px;
    background: transparent;
    border: 1px solid #2d4a6b;
    border-radius: 8px;
    color: #e2e8f0;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
    overflow: hidden;
    
    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: linear-gradient(145deg, transparent 30%, rgba(52, 243, 131, 0.03) 50%, transparent 70%);
      opacity: 0;
      transition: opacity 0.3s ease;
    }
    
    &::after {
      content: '';
      position: absolute;
      top: 2px;
      left: 2px;
      right: 2px;
      bottom: 2px;
      border-radius: 6px;
      background: linear-gradient(145deg, rgba(255, 255, 255, 0.02) 0%, transparent 50%, rgba(0, 0, 0, 0.1) 100%);
      pointer-events: none;
    }
    
    &:hover {
      background: transparent;
      border-color: #3d5a7d;
      transform: translateY(-1px);
      cursor: pointer;
      &::before {
        opacity: 1;
      }
    }
    
    &.is-active {
      background: transparent;
      color: #ffd700;
      
      .module-name {
        color: #ffd700;
      }
      
      &::before {
        background: linear-gradient(145deg, transparent 30%, rgba(52, 243, 131, 0.1) 50%, transparent 70%);
        opacity: 1;
      }
    }
    
    &.is-flashing {
      border-color: #34f383;
      animation: pulse-glow 2s ease-in-out infinite;
      background: transparent;
      
      &::before {
        background: linear-gradient(145deg, transparent 20%, rgba(52, 243, 131, 0.15) 50%, transparent 80%);
        opacity: 1;
      }
    }

    .button-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: flex-start; // Align items to the top
        height: 100%;
        padding: 4px;
        position: relative;
        z-index: 2;
        gap: 2px;
        
        .module-icon {
          width: 28px; // Slightly larger icon
          height: 28px;
          flex-shrink: 0;
          filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.5));
          opacity: 0.9;
          margin-top: 25px; // Margin from top indicators
          margin-bottom: 4px;
        }
        
        .module-name {
          font-size: 12px; // Larger font
          font-weight: 500;
          text-align: center;
          line-height: 1.3;
          text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8);
          letter-spacing: 0.2px;
          opacity: 0.95;
          word-break: break-word;
          max-width: 100%;
          width: 80px; // Increased width
          
          &.long-name {
            font-size: 12px;
            line-height: 1.3;
            max-height: 26px;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            word-wrap: break-word;
            white-space: normal;
            width: 120px;
          }
        }
        
        .module-status-indicators, .module-status-indicators-bottom {
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
          background: rgba(0, 0, 0, 0.4);
          border: 1px solid rgba(255, 255, 255, 0.1);
          border-radius: 12px; // Capsule shape
          padding: 2px 6px;
          line-height: 1;
          z-index: 10;
        }

        .module-status-indicators {
          position: absolute;
          top: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 100%; // Auto width based on content
          white-space: nowrap; // Prevent wrapping
          
        }

        .module-status-indicators-bottom {
          position: absolute;
          bottom: 4px;
          left: 50%;
          transform: translateX(-50%);
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .battery-indicator {
          display: flex;
          align-items: center;
          gap: 4px;
          margin-right: 10px;
          .battery-icon {
            width: 18px;
            height: 10px;
            border: 1px solid rgba(226, 232, 240, 0.8);
            border-radius: 2px;
            position: relative;
            background: rgba(0, 0, 0, 0.4);
            margin-right: 3px;
            &::after {
              content: '';
              position: absolute;
              right: -3px;
              top: 2px;
              width: 2px;
              height: 6px;
              background: rgba(226, 232, 240, 0.8);
              border-radius: 0 1px 1px 0;
            }
            
            .battery-level {
              height: 100%;
              border-radius: 1px;
              transition: all 0.3s ease;
            }
            
            &.battery-high .battery-level {
              background: linear-gradient(90deg, #34f383, #2dd4bf);
              box-shadow: 0 0 4px rgba(52, 243, 131, 0.6);
            }
            
            &.battery-medium .battery-level {
              background: linear-gradient(90deg, #fbbf24, #f59e0b);
              box-shadow: 0 0 4px rgba(251, 191, 36, 0.6);
            }
            
            &.battery-low .battery-level {
              background: linear-gradient(90deg, #ef4444, #dc2626);
              box-shadow: 0 0 4px rgba(239, 68, 68, 0.6);
            }
          }
        }

        .signal-indicator {
            display: flex;
            align-items: flex-end;
            gap: 2px;
            height: 10px;
            margin-right: 4px;

            .signal-bar {
              width: 3px;
              background-color: rgba(226, 232, 240, 0.3);
              border-radius: 1px;
              transition: background-color 0.3s ease;

              &:nth-child(1) { height: 20%; }
              &:nth-child(2) { height: 40%; }
              &:nth-child(3) { height: 60%; }
              &:nth-child(4) { height: 80%; }
              &:nth-child(5) { height: 100%; }
            }

            &.signal-excellent .signal-bar.active {
              background: linear-gradient(to top, #4CAF50, #8BC34A);
              box-shadow: 0 0 4px rgba(76, 175, 80, 0.6);
            }
            &.signal-good .signal-bar.active {
              background: linear-gradient(to top, #8BC34A, #CDDC39);
              box-shadow: 0 0 4px rgba(139, 195, 74, 0.6);
            }
            &.signal-fair .signal-bar.active {
              background: linear-gradient(to top, #FFC107, #FF9800);
              box-shadow: 0 0 4px rgba(255, 193, 7, 0.6);
            }
            &.signal-poor .signal-bar.active {
              background: linear-gradient(to top, #FF9800, #FF5722);
              box-shadow: 0 0 4px rgba(255, 152, 0, 0.6);
            }
            &.signal-none .signal-bar.active {
              background: linear-gradient(to top, #ef4444, #dc2626);
              box-shadow: 0 0 4px rgba(239, 68, 68, 0.6);
            }
          }

        .battery-text, .indicator-text {
          font-size: 11px; // Unified font size
          color: rgba(226, 232, 240, 0.95);
          font-weight: 600;
          text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
          display: flex;
          align-items: center;
        }
    }
  }
  
  @keyframes pulse-glow {
    0%, 100% {
      border-color: #34f383;
      opacity: 0.8;
    }
    50% {
      border-color: #34f383;
      opacity: 1;
    }
  }
}
</style>